<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Session;

class NewsController extends Controller
{
	
	// 资讯 详情 页
	public function newsDetail( $news_id, Request $request )
	{
		
		// 单条 详情
		$news = DB::table('news as n')
				-> select('n.*','a.name','c.name as category_name')
				-> where( 'n.id','=',$news_id )
				-> leftJoin( 'admin as a','a.id','=','n.admin_id' )
				-> leftJoin( 'category as c','c.id','=','n.category_id' )
				// 1草稿 2待审核 3审核通过 4推荐 5头条 6未通过
				-> whereIn( 'n.status',array(3,4,5) )
				-> first();
		
		// 没有这篇资讯
		if( empty($news) )
		{
			return view('errors.404');
		}
		
		// 资讯简短20字描述
		$pattern = "/<p[^>]*>(?:(?!<\/p>)[\s\S])*<\/p>/i";
		preg_match_all($pattern,$news->content,$arr);
		foreach( $arr[0] as $key => $str )
		{
			// 找到 img 标签 跳过
			if( strstr($str,'img')  || strstr($str,'<p><br/>') )
			{
				continue;
			}else
			{
				// 简短描述
				$desc =   rtrim( ltrim( $str,"<p>" ),"<br/></p>" ) ;
				$desc = str_replace("&nbsp;",'',$desc);
				$desc = mb_substr( $desc,0,30 );
				
				break;
			}
		}
		if( !isset($desc) )
		{
			$desc = '';
		}
		
		// 线上
		$str = str_replace( "/images" ,config('app.imgPath')."/images",$news->content);
		
		
		// 获取 全部 球队 
		$allTeam = DB::table('team_info')
			-> select('name','team_id')
			-> get();
		foreach( $allTeam as $key => $team_info  )
		{
			$str = str_replace( '"'.$team_info->name ,"",$str);
			$str = str_replace( "'".$team_info->name ,"",$str);
			$str = str_replace( $team_info->name ,"<a style='text-decoration:underline;color:red;' href='/teamdetail/".$team_info->team_id."'>".$team_info->name."</a>",$str);
		}
		
		// 获取 全部 球员
		$allPlayer = DB::table('player_info')
					-> select('name','player_id')
					-> get();
		foreach( $allPlayer as $key => $player_info  )
		{
			$str = str_replace( '"'.$player_info->name."：" ,"",$str);
			$str = str_replace( '"'.$player_info->name.":" ,"",$str);
			$str = str_replace( "'".$player_info->name."：" ,"",$str);
			$str = str_replace( "'".$player_info->name.":" ,"",$str);
			$str = str_replace( $player_info->name ,"<a style='text-decoration:underline;color:red;' href='/playerdetail/".$player_info->player_id."' >".$player_info->name."</a>",$str );
		}
		
		$str = str_replace( "<img" ,'<img title="'.$news->title.'" ',$str);
		$news->content = $str;
		
		// 获取全部赛程
		// 获取积分榜里的球队
		// $scorerank = DB::table('scorerank')
					// -> get();
		// 存放 所有球队的名字
		// $footName = array();
		// foreach( $scorerank as $key => $score )
		// {
			// 球队名字
			// if( !in_array($score -> name_zh,$footName) )
			// {
				// array_push($footName,$score -> name_zh);
			// }
		// }
		// 获取 全部赛程直播
		// $live_list = DB::table('saicheng')
				// -> select( 'id','c4T1','c4T2' )
				// -> where( 'c1','=','未开赛' )
				// 大于 此刻
				// -> where( 'c2','>',date('Y-m-d H:i:s') )
				// 先按 c2
				// -> orderBy('c2')
				// 先按 c3
				// -> orderBy('c3','desc')
				// -> get();
				
		// foreach( $live_list as $key=> $live_info )
		// {
			// 不存在的球队 先剔除
			// if( !in_array($live_info->c4T1,$footName) || !in_array($live_info->c4T2,$footName)  )
			// {
				// continue;
			// }else
			// {
			
				// $str = str_replace( $live_info->c4T1."vs".$live_info->c4T2,"<a style='text-decoration:underline;color:red;' href='/live_preview/".$live_info->id."'>".$live_info->c4T1."vs".$live_info->c4T2."</a>",$str);
				// $str = str_replace( $live_info->c4T1."VS".$live_info->c4T2,"<a style='text-decoration:underline;color:red;' href='/live_preview/".$live_info->id."'>".$live_info->c4T1."vs".$live_info->c4T2."</a>",$str);
				// $str = str_replace( $live_info->c4T1."与".$live_info->c4T2,"<a style='text-decoration:underline;color:red;' href='/live_preview/".$live_info->id."'>".$live_info->c4T1."vs".$live_info->c4T2."</a>",$str);
			// }
		// }
		
		
		
		// 获取 评论 
		$comments = DB::table('comments as c')
				-> select( 'u.name','c.create_at','c.content','c.id','c.user_id','c.good',DB::raw("replace(u.pic_url,'/images','".config('app.imgPath')."/images' ) as user_pic "  ) )
				-> leftJoin( 'user as u','u.id','=','c.user_id' )
				-> where( 'c.record_id','=',$news_id )
				// 资讯类型
				-> where( 'c.type','=',1 )
				// 评论 时间
				-> orderBy('c.create_at','desc')
				-> paginate(5);
		
		// 评论 总数
		$comments_total = DB::table('comments as c')
					-> where( 'record_id','=',$news_id )	
					// 资讯类型
					-> where( 'c.type','=',1 )					
					-> count();
		// 获取 评论 回复 
		$comments_reply = array();
		foreach( $comments as $key => $comment_info )
		{
			// 评论id
			$comment_id = $comment_info->id;
			$replys = DB::table('reply as r')
						-> select('r.*','u.name as username','uu.name as replyname',DB::raw("replace(uu.pic_url,'/images','".config('app.imgPath')."/images' ) as reply_user_pic ") )
						-> leftJoin('user as u','u.id','=','r.user_id')
						-> leftJoin('user as uu','uu.id','=','r.reply_user_id')
						-> where( 'r.comment_id','=',$comment_id )	
						// 回复 时间
						-> orderBy('r.create_at')
						-> get();
			$reply = array();
			foreach( $replys as $k => $reply_info )
			{
				
				$reply[$k]['id'] = $reply_info->id;
				$reply[$k]['comment_id'] = $reply_info->comment_id;
				$reply[$k]['good'] = $reply_info->good;
				$reply[$k]['user_id'] = $reply_info->user_id;
				$reply[$k]['content'] = $reply_info->content;
				$reply[$k]['reply_user_id'] = $reply_info->reply_user_id;
				$reply[$k]['create_at'] = $reply_info->create_at;
				$reply[$k]['username'] = $reply_info->username;
				$reply[$k]['replyname'] = $reply_info->replyname;
				$reply[$k]['reply_user_pic'] = $reply_info->reply_user_pic;
			}
			$comments_reply[$key] = $reply;
		}
		// 获取 推荐专区
		$recommend = $this -> getRecommend();

        // 资讯列表页详情 配置
        $webConfig = DB::table('webconfig')
            -> select('webName')
            -> where('id',1)
            -> first();

		// 详情 模板
		return view( 'news.detail',['webConfig'=>$webConfig,'news'=>$news,'recommend'=>$recommend,'comments'=>$comments,'comments_total'=>$comments_total,'comments_reply'=>$comments_reply,'desc'=>$desc ] );
		
		
	}
	
	
	// 获取 推荐专区
	public function getRecommend()
	{
		// 推荐
		$tuijian = DB::table('news as n')
				-> select('n.title','n.id','np.pic_url')
				-> leftJoin('news_pic as np','np.news_id','=','n.id')
				// 1草稿 2待审核 3审核通过 4推荐 5头条 6未通过
				-> where( 'n.status','=',4 )
				// 封面
				-> where( 'np.status','=',1 )
				-> orderBy('n.create_at','desc')
				-> take(10)
				-> get();
		$recommend = array();
		foreach( $tuijian as $key => $info  )
		{
			
			$recommend[$key]['id'] = $info->id;
			$recommend[$key]['title'] = $info->title;
			// 线上 图片 地址 
			$str = str_replace("/images",config('app.imgPath')."/images",$info->pic_url);
			$recommend[$key]['pic_url'] = $str;
			
		}

		return $recommend;
	}
	
	
	// 资讯 列表
	public function newsList( $category_id='all',$tag='all',Request $request )
	{
	
		
		
		// 1. 获取 全部资讯分类
		$news_category = DB::table('category')
				-> select('id','name')
				// 足球资讯 大分类下
				-> where('pid',1)
				-> orderBy('id')
				-> get();
		
		if( $category_id=='all' )
		{
			// 获取全部资讯
			$one = "!=";
			$two = "";
		}else
		{
			// 特定分类资讯
			$one = "=";
			$two = $category_id;
			
		}
		$allow = array(2,3,4,5,6);
		// 不在 查看范围内 默认全部
		if( !in_array($category_id,$allow) )
		{
			// 获取全部资讯
			$one = "!=";
			$two = "";
		}
		
		// 获取 搜索 内容
		$keyTitle = $request->input('keyTitle',"");
		
		
		if( empty($keyTitle) )
		{
			// 为空 说明没有搜索
			$three = 'n.id';
			$four = '!=';
			$five = '0';
			if( Session::get('commonSearch') )
			{
				Session::forget('commonSearch');
			}
			if( Session::get('commonSelect') )
			{
				Session::forget('commonSelect');
				// 选中的 资讯类型
				Session::put('commonSelect',1);
			}
			
		}else
		{
			// 是 资讯 文章
			$three = 'n.title';
			$four = 'like';
			$five = '%'.$keyTitle.'%';
			Session::put('commonSearch',$keyTitle);
			if( Session::get('commonSelect') )
			{
				Session::forget('commonSelect');
				// 选中的资讯类型
				Session::put('commonSelect',1);
			}
			
			
		}
		
		
		// 标签内容
		// $tag = $request->input('tag',"");
		// if( !empty($tag) )
		// {
			// $six = "tags";
			// $seven = "like";
			// $eight = "%".$tag."%";
		// }else
		// {
			// $six = 'n.id';
			// $seven = '!=';
			// $eight = '0';
		// }
		
		
		// 2. 获取 资讯 展示
		if( $tag=='all' )
		{
			$all_news = DB::table('news as n')
				-> select( 'n.id','n.title','np.pic_url','c.name as category','n.content','n.from','n.good','n.category_id','n.create_at')
				-> leftJoin('news_pic as np','np.news_id','=','n.id')
				-> leftJoin('category as c','c.id','=','n.category_id')
				// 封面
				-> where( 'np.status','=',1 )
				-> where( 'c.id',$one,$two )
				// 搜索 条件
				-> where( $three,$four,$five )
				// -> where( $six,$seven,$eight )
				// 按 发布 时间 排序
				-> orderBy('n.create_at','desc')
				-> paginate(10);
		}else
		{
			
			// 有标签
			$all_news = DB::table('news as n')
				-> select( 'n.id','n.title','np.pic_url','c.name as category','n.content','n.from','n.good','n.category_id','n.create_at')
				-> leftJoin('news_pic as np','np.news_id','=','n.id')
				-> leftJoin('category as c','c.id','=','n.category_id')
				-> leftJoin('tag_record as tr','tr.record_id','=','n.id')
				// 封面
				-> where( 'np.status','=',1 )
				// 资讯
				-> where( 'tr.type','=',1 )
				-> where( 'tr.tag_id','=',$tag )
				-> where( 'c.id',$one,$two )
				// 搜索 条件
				-> where( $three,$four,$five )
				// -> where( $six,$seven,$eight )
				// 按 发布 时间 排序
				-> orderBy('n.create_at','desc')
				-> paginate(10);
		
		}
		
		
		$page_news = array();
		foreach( $all_news as $key => $news_info )
		{
			$news = array();
			// 获取对应标签
			$tags = DB::table('tag_record as tr')
				-> select('t.id','t.name')
				-> leftJoin('tag as t','t.id','=','tr.tag_id')
				// 资讯 
				-> where('tr.type',1)
				-> where('tr.record_id',$news_info->id)
				-> get();
			
			if( !empty($tags) )
			{
				// 存在标签 一个或多个
				$all_tag = array();
				foreach( $tags as $tagkey => $tagInfo )
				{
					$tag_str = array();
					// 标签名
					$tag_str['name'] = $tagInfo->name;
					// 标签id
					$tag_str['tag_id'] = $tagInfo->id;
					$all_tag[$tagkey] = $tag_str;
				}
				// 标签
				$news['tags']= $all_tag;
			}else
			{
				// 不存在 标签
				$news['tags'] = array();
			}
			// dd($news['tags']);
			$news['id']= $news_info->id;
			$news['title']= $news_info->title;
			$news['from']= $news_info->from;
			$news['good']= $news_info->good;
			$news['category_id']= $news_info->category_id;
			$diff = time()-strtotime($news_info->create_at);
			// 1个小时
			$hour = 60*60;
			$result = $diff/$hour;
			// 24小时内
			if( $result<1 )
			{
				$news['create_time']= ceil($diff/60).'分钟前';
			}elseif( $result < 24 )
			{
				$news['create_time']= ceil($diff/$hour)."小时前";
			}elseif( $result>=24 )
			{
				// 大于24小时
				$news['create_time']= floor($result/24)."天前";
			}
			
			// 分类
			$news['category']= $news_info->category;
			$pattern = "/<p[^>]*>(?:(?!<\/p>)[\s\S])*<\/p>/i";
			preg_match_all($pattern,$news_info->content,$arr);
			foreach($arr[0] as $keyy => $str)
			{
				// 找到 img 标签 跳过
				if( strstr($str,'img') || strstr($str,'<p><br/>')   )
				{
					continue;
				}else
				{
					$patt = "/<p[^>]*>(?:(?!<\/p>)[\s\S])*<\/p>/i";
					preg_match_all($patt,$str,$array);
					// 简短描述
					// $news['content']= rtrim( ltrim( $str,"<p>" ),"<br/></p>" );
					$news['content']= $array[0][0];
					break;
				}
			}
			// dd($arr[0]);
			
			// 评论 计数
			$news['comments_total'] = DB::table('comments')
							// 
							-> where( 'record_id','=',$news_info->id )
							// 资讯 类型
							-> where( 'type','=',1 )		
							-> count();
			// 线上 图片 地址 
			$str = str_replace("/images",config('app.imgPath')."/images",$news_info->pic_url);
			$news['pic_url']= $str;
			$page_news[$key] = $news;
		}
	
		// 缓存一分钟
		// Cache::put( 'all_news',$all_news,1);
		
		
		if( $category_id=='all' )
		{
			$category_info = DB::table('category')
					-> where('id','=',1 )
					-> first();
		}else
		{
			$category_info = DB::table('category')
					-> where('id','=',$category_id )
					-> first();
		}
		
		
		// 获取 推荐专区
		$recommend = $this -> getRecommend();
		
		// 资讯列表页 配置
		$webConfig = DB::table('webconfig')
			-> select('webName')
			-> where('id',1)
			-> first();

		return view( 'news.list',['recommend'=>$recommend,'page_news'=>$page_news,'all_news'=>$all_news,'news_category'=>$news_category,'category_id'=>$category_id,'category_info'=>$category_info,'keyTitle'=>$keyTitle,'webConfig'=>$webConfig ]  );
		
	}
	
	
	
	
}
